package com.java2007.hotel.dao.impl;

import com.java2007.hotel.dao.FoodDao;
import com.java2007.hotel.pojo.Food;
import com.java2007.hotel.utils.JdbcUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author ghy
 * @version 1.0
 * @date 2021-01-22
 */
public class FoodDaoImpl implements FoodDao {
    @Override
    public int save(Food food) throws SQLException {
        QueryRunner runner = new QueryRunner();
        String sql = "INSERT INTO t_food (`type_id`,`food_name`,`price`,`vip_price`,`image`,`food_desc`) VALUES (?,?,?,?,?,?)";
        return runner.update(JdbcUtil.getConnection(), sql, food.getTypeId(), food.getFoodName(),food.getPrice(),
                food.getVipPrice(), food.getImage(), food.getFoodDesc());
    }

    @Override
    public Food findById(int id) throws SQLException {
        QueryRunner runner = new QueryRunner(JdbcUtil.getDataSource());
        String sql = "SELECT `food_id` foodId, `type_id` typeId, `food_name` foodName,`price`,`vip_price` vipPrice,`image`,`food_desc` foodDesc FROM `t_food` WHERE food_id = ?";
        return runner.query(sql, new BeanHandler<>(Food.class), id);
    }

    @Override
    public List<Food> findByPage(Integer start, Integer pageSize) throws SQLException {
        QueryRunner runner = new QueryRunner(JdbcUtil.getDataSource());
        String sql = "SELECT `food_id` foodId, `type_id` typeId, `food_name` foodName,`price`,`vip_price` vipPrice,`image`,`food_desc` foodDesc FROM `t_food` limit ?,?";
        return runner.query(sql, new BeanListHandler<>(Food.class), start, pageSize);
    }

    @Override
    public Long getCount() throws SQLException {
        QueryRunner runner = new QueryRunner(JdbcUtil.getDataSource());
        String sql = "SELECT count(1) FROM `t_food`";
        return runner.query(sql, new ScalarHandler<Long>());
    }


}
